/**
 * Created by Baggio on 2017-11-22.
 */
$(function () {

    createPayment();


    $(".btn").click(function () {
        var orderId = $("#orderId").val();
        var price = $("#price").val();


        var consigneeName = $('input:text[name="consigneeName"]').val();
        var consigneePhone = $('input:text[name="consigneePhone"]').val();
        var consigneeAddress = $("#address").val();
        if (consigneeName == '') {
            alert("收货人姓名不能为空");
            return;
        }
        if (consigneePhone == '') {
            alert("收货人电话不能为空");
            return;
        }
        if (checkMobile(consigneePhone)) {
            alert("收货人电话格式不对！");
            return;
        }
        if (consigneeAddress == '') {
            alert("收货人地址不能为空");
            return;
        }

        var tid = $('input:hidden[name="tid"]').val();
        var paymentList = getPaymentList();
        var postData = {
            "orderId": orderId,
            "paymentListJSON": JSON.stringify(paymentList),
            "consigneeInfo.consigneeAddress": consigneeAddress,
            "consigneeInfo.consigneePhone": consigneePhone,
            "consigneeInfo.consigneeName": consigneeName,
            "consigneeInfo.tid": tid
        };
        console.log("postData=====>>>");
        console.log(postData);
        $.ajax({
            type: "post",
            url: "/pay/toPay.html",
            dataType: "json",
            async: false,
            data: postData,
            success: function (res) {
                console.log("=========================>>>>>");
                console.log(postData)
                console.log(res);
                if (res.code != 1) {
                    alert(res.msg);
                    return;
                }

                var data = res.data;
                for (var i = 0; i < data.length; i++) {

                    if (data[i].payMode == 9) {
                        if (data[i].payStatus == 1) {
                            alert("兑换成功！");
                        }
                    }
                    if (data[i].payMode == 6) {
                        if (data[i].payStatus == 0) {
                            var wxPayData = data[i].map;
                            weChatPayinit(wxPayData);
                        }
                    }
                }
            }
        });
    });


});
function getPaymentList() {
    var paymentList = [];
    $(".payMode").find("div").find(".active").find("span").each(function () {
        console.log($(this).attr("payPrice"));
        console.log($(this).attr("payMode"));
        var payPrice = $(this).attr("payPrice");
        var payMode = $(this).attr("payMode");
        var payment = {"payMode": payMode, "price": payPrice, "payType": 1}
        paymentList.push(payment);
    });
    console.log("paymentList==================>>>>");
    console.log(paymentList);
    return paymentList;
}
function createPayment() {
    var orderPrice = $("#price").val();
    var payedPrice = 0;
    var postData = {};
    $.ajax({
        type: "post",
        url: "/user/getUserAccountList.html",
        dataType: "json",
        async: false,
        data: postData,
        success: function (res) {
            console.log(res);
            if (res.code != 1) {
                alert(res.msg);
                return;
            }
            var html = "";
            for (var i = 0; i < res.data.length; i++) {
                html += "<div class='active'>";
                console.log(res.data[i]);
                if (res.data[i].accountType == 3) {
                    var money = res.data[i].money;
                    if (orderPrice > money) {
                        payedPrice += Number(money);
                    }
                    else if (orderPrice <= money) {
                        payedPrice += Number(orderPrice);
                    }
                    html += "<span payPrice='" + payedPrice + "' payMode='9'>兑换("+payedPrice+")</span>";
                }
                html += "</div>";

            }

            if (payedPrice < orderPrice) {
                console.log(payedPrice + "+<===============================================================>++" + orderPrice);
                payedPrice=orderPrice-payedPrice;
                html += "<div class='active'>";

                html += "<span payPrice='" + payedPrice + "' payMode='6'>微信支付"+payedPrice+")</span>";
                html += "</div>";
            }

            $(".payMode").find("div").html(html);
        }

    });
}

function weChatPayinit(wxPayData) {
    //alert(wxPayData.appId);
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: wxPayData.appId, // 必填，公众号的唯一标识
        timestamp: wxPayData.wxConfigTimeStamp, // 必填，生成签名的时间戳
        nonceStr: wxPayData.wxConfigNonceStr, // 必填，生成签名的随机串
        signature: wxPayData.Signature,// 必填，签名，见附录1
        jsApiList: ['chooseWXPay'],
        success: function (res) {
            // 支付成功后的回调函数c
            //  alert("succJSON====>" + JSON.stringify(res));
        },
        fail: function (msg) {
            // alert("fail-=>" + JSON.stringify(msg));
        }
        // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });
    wx.ready(function () {
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        callpay(wxPayData);
    });
    wx.error(function (res) {
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        //  alert("erro==>" + JSON.stringify(res));
    });

}
function callpay(wxPayData) {
    wx.chooseWXPay({
        "appId": wxPayData.appId,//appid
        "timestamp": wxPayData.wxJsApiParamTimeStamp, //时间戳，自1970年以来的秒数
        "nonceStr": wxPayData.wxJsApiParamNonceStr, //随机串
        "package": wxPayData.PackAge,
        "signType": "MD5", //微信签名方式：
        "paySign": wxPayData.PaySign, //微信签名

        success: function (res) {
            // 支付成功后的回调函数c
            // alert(JSON.stringify(msg));
            var orderId = $("#orderId").val();
            alert("支付成功！");
            var url = "/pay/payResult.html?ordrId=" + orderId;
            location.href = url;
        },
        fail: function (msg) {
            alert("pay eerro");
            //  alert(JSON.stringify(msg));
        }
    });
}

function checkJsApi() {

    wx.checkJsApi({
        jsApiList: ['chooseImage', 'chooseWXPay'],// 需要检测的JS接口列表，所有JS接口列表见附录2,
        success: function (res) {
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
            alert(JSON.stringify(res));
        }
    });
}